import baostock as bs
import pandas as pd

def bs_k_data_stock(code_val='sz.000651', start_val='2009-01-01', end_val='2020-10-28',
                freq_val='d', adjust_val='3'):
    lg = bs.login()
    # 获取历史行情数据
    fields = "date,open,high,low,close,volume"
    df_bs = bs.query_history_k_data(code_val, fields, start_date=start_val,
                end_date=end_val, frequency=freq_val, adjustflag=adjust_val)
    # frequency="d" 取日k线， adjustflag="3"默认不复权 1::后复权 2:前复权

    data_list=[]
    while(df_bs.error_code == '0') & df_bs.next():
        # 获取一条记录，将记录合并在一起
        data_list.append(df_bs.get_row_data())

    result = pd.DataFrame(data_list, columns=df_bs.fields)
    result.close = result.close.astype('float64')
    result.open = result.open.astype('float64')
    result.low = result.low.astype('float64')
    result.high = result.high.astype('float64')
    result.volume = result.volume.astype('int')
    result.volume = result.volume/100 # 单位转换: 股-手
    
    result.date = pd.DatetimeIndex(result.date)
    result.set_index("date", drop=True, inplace=True)
    result.index = result.index.set_names('Date')

    recon_data = {'Open': result.open, 
            'Close':result.close,
            'High':result.high,
            'Low':result.low,
            'Volume':result.volume}
    df_recon = pd.DataFrame(recon_data)
    # 退出系统
    bs.logout()
    return df_recon

if __name__ == "__main__":
    
    print(bs_k_data_stock().head())

    